package server_thread;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class FileDownloadServerThread implements Runnable{
	private Socket socket;
	
	public FileDownloadServerThread(Socket socket){
		this.socket = socket;
	}

	public void run() {
		OutputStream out;
		try {
			out = socket.getOutputStream();
			
			InputStream in = socket.getInputStream();
			out.write("please input filename with path\r\n".getBytes());
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			BufferedOutputStream outputStream = new BufferedOutputStream(out);
			String name; 
			
		
			while((name=reader.readLine())!=null){
				System.out.println(name);
				File file = new File("ftp/"+name);
				if (!file.exists()) {
					outputStream.write("file not extis\n".getBytes());
					outputStream.flush();
					continue;
					
				}
				
				BufferedInputStream bInputStream = new BufferedInputStream((new FileInputStream("ftp/"+name)));
				outputStream.write(("200ok\n").getBytes());
				outputStream.write((bInputStream.available()+"\n").getBytes());
				outputStream.flush();
				int m=0;
				byte[] buf = new byte[20];
				while ((m=bInputStream.read(buf))!=-1) {
					outputStream.write(buf,0,m);
					
				}
				bInputStream.close();
				outputStream.flush();
				System.out.println("finsh");
			}
			
			out.close();
			reader.close();
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	

}
